package com.etonenet.service.system;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.data.domain.Page;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.etonenet.entity.system.SystemNode;
import com.etonenet.repository.system.SystemNodeRepository;
import com.etonenet.util.StringUtil;

import esms.etonenet.boss1069.web.UrlConstants;

@Service
public class MenuService implements IMenuService {

	private StringBuffer menuHtml;

	private Map<String, String> nodePathName = new HashMap<String, String>();

	@Resource
	private SystemNodeRepository sysnodeEm;

	public SystemNode findByNodeId(Long id) {

		return sysnodeEm.findOne(id);
	}

	public List<SystemNode> listTreegrid() {

//		return sysnodeEm.listAllTreegrid();
		return sysnodeEm.listAllRoot();
	}

	public SystemNode save(SystemNode sysnode) {

		SystemNode sn = sysnodeEm.save(sysnode);
		initMenu();

		return sn;
	}

	public SystemNode update(SystemNode sysnode) {

		SystemNode update = sysnodeEm.findOne(sysnode.getSystemNodeId());
		if (update != null) {

			update.setNodeName(sysnode.getNodeName());
			update.setDisplayOrder(sysnode.getDisplayOrder());
			update.setUrl(sysnode.getUrl());
			update.setNodeType(sysnode.getNodeType());
			update.setIcon(sysnode.getIcon());

			sysnodeEm.save(update);
		}
		initMenu();
		return update;
	}

	public void del(Long nodeId) {

		SystemNode del = new SystemNode();
		del.setSystemNodeId(nodeId);
		sysnodeEm.delete(del);
		initMenu();
	}

	@PostConstruct
	public void initMenu() {

		menuHtml = new StringBuffer();

		Page<SystemNode> rootNodes = sysnodeEm.findAll(new Specification<SystemNode>() {

			@Override
			public Predicate toPredicate(Root<SystemNode> root, CriteriaQuery<?> query, CriteriaBuilder cb) {

				List<Predicate> p = new ArrayList<Predicate>();
				p.add(cb.isNull(root.get("parent")));
				p.add(cb.equal(root.get("nodeType"), 0));

				query.orderBy(cb.asc(root.get("displayOrder")));

				Predicate[] predicates = new Predicate[p.size()];
				p.toArray(predicates);
				return query.where(predicates).getRestriction();
			}
		}, null);

		for (SystemNode node : rootNodes) {
			getTreeNodes(node, 1);
		}

		menuHtml.append("<li>")
				.append("<a href=\"#\"><i class=\"fa fa-cogs\"></i> <span class=\"name\">系统设置</span><span class=\"fa expand\"></span></a>")
				.append("<ul class=\"nav nav-second-level collapse\">")
				.append("<li><a href=\"javascript:menuTo('" + UrlConstants.SYSTEM_NODE_INDEX
						+ "','系统节点管理')\">系统节点管理</a></li>")
				.append("<li><a href=\"javascript:menuTo('" + UrlConstants.SYSTEM_LOG_INDEX
						+ "','日志管理')\">日志管理</a></li>")
				.append("<li><a href=\"javascript:menuTo('" + UrlConstants.SYSTEM_AUTH_INDEX
						+ "','权限管理')\">权限管理</a></li>")
				.append("</ul>").append("</li>");

	}

	private void getTreeNodes(SystemNode node, int childLevel) {

		if (node != null) {

			menuHtml.append("<li>");
			String href = "#";
			if (StringUtil.isNotEmpty(node.getUrl()))
				href = node.getUrl();

			menuHtml.append("<a href=\"javascript:menuTo('" + href + "','" + node.getNodeName() + "')\">");
			if (childLevel == 1) {
				String icon = node.getIcon();
				if (StringUtil.isEmpty(icon))
					icon = "fa-folder";
				menuHtml.append("<i class=\"fa " + icon + " \"></i>")
						.append("<span class=\"name\">" + node.getNodeName() + "</span>");
			} else
				menuHtml.append(node.getNodeName());

			int c = sysnodeEm.countChildren(node.getSystemNodeId()).intValue();
			if (c > 0)
				menuHtml.append("<span class=\"fa expand\"></span>");
			menuHtml.append("</a>");

			if (c > 0) {
				childLevel++;
				String level = "";
				if (childLevel == 2)
					level = "second";
				else
					level = "third";

				menuHtml.append("<ul class=\"nav nav-" + level + "-level collapse\">");
				for (SystemNode child : sysnodeEm.listChildren(node.getSystemNodeId())) {
					getTreeNodes(child, childLevel);
				}
				menuHtml.append("</ul>");
				menuHtml.append("</li>");
			}

			menuHtml.append("</li>");
		} else
			return;
	}

	public StringBuffer getMenuHtml() {
		return menuHtml;
	}

	/**
	 * 传入url获得这个所在url完整的node路径名，各节点之间使用/分割
	 * 
	 * @param url
	 * @return
	 */
	public String getNodePathName(String url) {

		String pathName = nodePathName.get(url);
		if (!StringUtil.isNotEmpty(pathName)) {
			SystemNode node = sysnodeEm.findNodeByUrl(url);

			while (node != null) {
				pathName = "/" + node.getNodeName() + (pathName == null ? "" : pathName);
				node = node.getParent();
			}
			if (pathName != null) {
				pathName = pathName.substring("/".length());
			}

			nodePathName.put(url, pathName);
		}
		return pathName;
	}
}
